package top.kpromise.note.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.builders.*;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.service.ResponseMessage;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Value("${swagger.production}")
    private boolean production;

    @Bean
    public Docket createRestApi() {
        List<ResponseMessage> responseMessageList = new ArrayList<>();
        responseMessageList.add(new ResponseMessageBuilder().code(400).message("token过期")
                .responseModel(new ModelRef("string")).build());
        responseMessageList.add(new ResponseMessageBuilder().code(401).message("参数校验异常")
                .responseModel(new ModelRef("string")).build());
        responseMessageList.add(new ResponseMessageBuilder().code(500).message("业务逻辑错误")
                .responseModel(new ModelRef("string")).build());

        return new Docket(DocumentationType.SWAGGER_2)
                .enable(!production)
                .globalResponseMessage(RequestMethod.GET, responseMessageList)
                .globalResponseMessage(RequestMethod.POST, responseMessageList)
                .globalResponseMessage(RequestMethod.PUT, responseMessageList)
                .globalResponseMessage(RequestMethod.DELETE, responseMessageList)
                .globalOperationParameters(headerInfo())
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
                .paths(PathSelectors.any()).build();
    }

    private List<Parameter> headerInfo() {
        ParameterBuilder headers = new ParameterBuilder();
        List<Parameter> parameters = new ArrayList<>();
        headers.name("Authorization").description("登录后返回的Authorization")
                .modelRef(new ModelRef("string"))
                .parameterType("header").required(false)
                .defaultValue("b5a14a1f-cef6-469f-876b-b2204cc9b46f").build();
        parameters.add(headers.build());
        return parameters;
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("k-note restful apis")
                .description("个人知识管理平台")
                .termsOfServiceUrl("")
                .version("1.0.0")
                .build();
    }
}